import os
import cv2
from werkzeug.utils import secure_filename
from datetime import datetime
import hashlib
import shutil
from moviepy.video.io.VideoFileClip import VideoFileClip
import uuid
from PIL import Image
import numpy as np
import imagehash

target_path = r'E:\test'
tmp_remove_path = os.path.join(target_path, "file_to_remove")
os.makedirs(tmp_remove_path, exist_ok=True)

def find_files(directory, extensions=('.mp4', '.avi', '.mov')):
    """
    递归查找目录下所有指定扩展名的视频文件
    :param directory: 要搜索的根目录路径
    :param extensions: 包含目标扩展名的元组
    :return: 匹配文件的完整路径列表
    """
    output_files = []
    for root, _, files in os.walk(directory):
        for file in files:
            if file.lower().endswith(extensions):
                output_files.append(os.path.join(root, file))
    return output_files

def get_hash(video_path):
    cap = cv2.VideoCapture(video_path)
    success, image = cap.read()
    if success:
        return dhash(image)
    return None

def dhash(image, hash_size=8):
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    resized = cv2.resize(gray, (hash_size+1, hash_size))
    
    cv2.imwrite(os.path.join(target_path, str(uuid.uuid4()) + ".jpg"), resized)
    diff = resized[:,1:] > resized[:,:-1]
    return sum([2**i for (i,v) in enumerate(diff.flatten()) if v])

def fetch_all_video_info(video_list):
    ret = {}
    for i, v in enumerate(video_list):
        hash_val = get_hash(v)
        ret.setdefault(hash_val, []).append(v)
        print(f"解析第{i}个文件，{v}, 总共{len(video_list)}个文件, {hash_val}")
    return ret

def move_depulicate_files(file_map):
    count = 1
    all_num = len(file_map)
    for _, v in file_map.items():
        count += 1
        print(f"正在检查第{count}个文件组，总共{all_num}个")
        if len(v) < 2:
            continue
        video_len_list = [get_video_duration(x) for x in v]
        if len(set(video_len_list)) > 1:
            continue
        size_list = [(x, os.path.getsize(x)) for x in v]
        target_list = sorted(size_list, key=lambda x: (len(x[0]), -x[1]))
        for i, _ in target_list[1:]:
            full_name = os.path.basename(i)
            shutil.move(i, os.path.join(tmp_remove_path, full_name))
            print(f"正在临时删除文件{i}, 保留的文件为{target_list[0][0]}")


def get_video_duration(file_path):
    with VideoFileClip(file_path) as video:
        return video.duration

def get_content_hash(video_path, sample_frames=5):
    cap = cv2.VideoCapture(video_path)
    hashes = []
    for _ in range(sample_frames):
        ret, frame = cap.read()
        if not ret: break
        img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
        hashes.append(str(imagehash.average_hash(img)))
    cap.release()
    return ''.join(sorted(hashes))

def is_same_video(file1, file2):
    # 比较内容哈希
    if get_content_hash(file1) != get_content_hash(file2):
        return False
    
    # 验证时长等元数据
    cap1 = cv2.VideoCapture(file1)
    cap2 = cv2.VideoCapture(file2)
    duration_match = abs(cap1.get(cv2.CAP_PROP_FRAME_COUNT)/cap1.get(cv2.CAP_PROP_FPS) - 
                        cap2.get(cv2.CAP_PROP_FRAME_COUNT)/cap2.get(cv2.CAP_PROP_FPS)) < 0.1
    cap1.release()
    cap2.release()
    
    return duration_match


if __name__ == '__main__':
    pass
